import './todoList.css'
import { useSelector, useDispatch } from 'react-redux'
import { addTodo } from '../../store/modules/todoListStore.js'
import { delTodo } from '../../store/modules/todoListStore.js'
import { toggleOne } from '../../store/modules/todoListStore.js'
import { toggleAll } from '../../store/modules/todoListStore.js'
import { useRef } from 'react'

function TodoList() {
    const todoList = useSelector(state => state.todoList)
    const dispatch = useDispatch()
    const inputRef = useRef(null)

    // 判断是否全选（用于控制 toggle-all 状态）
    const isAllCompleted =
        todoList.list.length > 0 && todoList.list.every(item => item.completed)

    return (
        <section className="todoapp">
            <header className="header">
                <h1>todos</h1>
                <input
                    className="new-todo"
                    autoFocus
                    autoComplete="off"
                    placeholder="What needs to be done?"
                    ref={inputRef}
                    onKeyDown={(e) => {
                        if (e.key === 'Enter' && inputRef.current.value) {
                            dispatch(addTodo(inputRef.current.value))
                            inputRef.current.value = ''
                        }
                    }}
                />
            </header>

            <section className="main">
                <input
                    id="toggle-all"
                    className="toggle-all"
                    type="checkbox"
                    onChange={() => dispatch(toggleAll())}
                    checked={isAllCompleted}
                />
                <label htmlFor="toggle-all"></label>

                <ul className="todo-list">
                    {todoList.list.map(item => (
                        <li
                            className={`todo ${item.completed ? 'completed' : ''}`}
                            key={item.id}
                        >
                            <div className="view">
                                <input
                                    className="toggle"
                                    type="checkbox"
                                    checked={item.completed}
                                    onChange={() => dispatch(toggleOne(item.id))}
                                />
                                <label>{item.name}</label>
                                <button
                                    className="destroy"
                                    onClick={() => dispatch(delTodo(item.id))}
                                ></button>
                            </div>
                        </li>
                    ))}
                </ul>
            </section>
        </section>
    )
}

export default TodoList;
